package staticClass.score;

import staticClass.sql.JDBCUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class SubmitExam {

    public static void UpdateScore(String email, int tid, int score) {
        Connection conn = JDBCUtil.getConn();
        PreparedStatement ps = null;
        try {
            conn.setAutoCommit(false);
            String sql = "update grade set last = ?, timesT = timesT + 1, mast = IF(? > mast, ?, mast) " +
                    "where examid = ? and userid = (select id from user where email = ?)";
            ps = conn.prepareStatement(sql);
            ps.setInt(1, score);
            ps.setInt(2, score);
            ps.setInt(3, score);
            ps.setInt(4, tid);
            ps.setString(5, email);
            ps.executeUpdate();
            conn.commit();
        } catch (SQLException throwables) {
            try {
                conn.setAutoCommit(false);
                String sql = "insert into grade(userid, examid, last, mast, timesT) values (" +
                        "(select id from user where email = ?), ?, ?, ?, 1)";
                ps = conn.prepareStatement(sql);
                ps.setString(1, email);
                ps.setInt(2, tid);
                ps.setInt(3, score);
                ps.setInt(4, score);
                ps.executeUpdate();
                conn.commit();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        } finally {
            JDBCUtil.replace(conn, ps, null);
        }

    }
}
